import Shape from './shape.js';
import {
  createText,
  randomCase,
  letterGenerator,
} from './util.js';

const isLive = {};
const Text = ARE.Text;

export default class Queue {
  constructor({
    stage,
    queue = {},
    range,
    total,
  }){
    this.stage = stage;
    this.queue = queue;
    this.range = range;
    this.total = total;

    this.charGen = letterGenerator(this.range);
  }

  getItem( id ){
    return this.queue[id];
  }
  getLiveLength(){
    return Object.keys(isLive).filter( id=> isLive[id]).length;
  }

  isExist(id){
    return !! this.getItem( id.toLowerCase() ) || this.getItem( id.toUpperCase() );
  }

  isExactExist(id){
    return !! this.getItem( id );
  }

  add( fontBoundWidth ){
    const char = this.charGen();
    const id = randomCase(char);
    isLive[id] = true; // 复活
    let shape;
    if( this.isExactExist(id) ){
      shape = this.queue[id];
    }
    else{
      shape = new Shape({
        text: createText(Text, id, {
          fontSize: `100px`,
        }),
      });
      this.queue[id] = shape;
      this.stage.add(shape.text);
    }
    shape.birth(fontBoundWidth);
  }

  hide( id ){
    const ids = Object.keys( isLive ).filter( id => isLive[id]);
    const lower = id.toLowerCase();
    const upper = id.toUpperCase();
    [lower, upper].forEach( id=>{
      if( ids.includes( id ) ){
        isLive[id] = false;
        this.getItem(id).die();
      }
    });
  }

  senesce({
    step,
  }){
    Object.keys( this.queue ).forEach( id =>{
      if (isLive[id]) {
        const shape = this.getItem(id);
        if( shape.isOld() ){
          isLive[id] = false;
          shape.die();
        }
        else{
          shape.senesce({
            step,
          });
        }
      }
    });
  }

  spawn(fontBoundWidth){
    if (this.getLiveLength() < this.total) {
      this.add(fontBoundWidth);
    }
  }
}